﻿// --------------------------------------------------------------------------------------------------------------------
// <copyright file="WorkflowHelper.cs" company="Open Source">
//   MIT License
// </copyright>
// <summary>
//   Defines the WorkflowHelper type.
// </summary>
// --------------------------------------------------------------------------------------------------------------------

namespace Contour.Contrib
{
    using System.Net.Mail;
    using System.Web;
    using System.Xml;
    using System.Xml.XPath;

    /// <summary>
    /// The workflow helper.
    /// </summary>
    public class WorkflowHelper
    {
        #region Public Methods

        /// <summary>
        /// The add attachment to mail.
        /// </summary>
        /// <param name="mailMessage">
        /// The mail message.
        /// </param>
        /// <param name="xml">
        /// The xml node
        /// </param>
        public static void AddAttachmentToMail(MailMessage mailMessage, XmlNode xml)
        {
            if (xml == null)
            {
                return;
            }

            XPathNavigator navigator = xml.CreateNavigator();
            XPathExpression selectExpression = navigator.Compile("//fields/child::*");
            selectExpression.AddSort("@pageindex", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Number);
            selectExpression.AddSort("@fieldsetindex", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Number);
            selectExpression.AddSort("@sortorder", XmlSortOrder.Ascending, XmlCaseOrder.None, string.Empty, XmlDataType.Number);
            XPathNodeIterator nodeIterator = navigator.Select(selectExpression);
            while (nodeIterator.MoveNext())
            {
                if (nodeIterator.Current == null)
                {
                    continue;
                }

                XPathNavigator node = nodeIterator.Current.SelectSingleNode(".//value");
                if (node == null || !node.Value.Contains("/umbraco/plugins/umbracoContour/files/"))
                {
                    continue;
                }

                // add attachment
                string filelocation = HttpContext.Current.Server.MapPath(node.Value);
                mailMessage.Attachments.Add(new Attachment(filelocation));
            }
        }

        #endregion
    }
}